
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.mk.transaction.returtowarehouse;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionOutReturToMainKitchen;
import com.ronsicecream.pos.entities.PosTransactionOutReturToMkDetail;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.mk.transaction.returtowarehousedetail.ReturDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class Retur extends Page{
    private Field returId;
    
    private Field returDate;
    
    private Field returNumber;
    
    private Field returQuantity;
    
    private Field returDescription;
    
    private Field returTimestamp;
    
    private Field returUserId;
    
    private Field returUnitId;
    
    private Field returReceiptId;
    
    private Field returPosUnitId;
    
    private Field returRegionalId;
    

    public Retur() {
        super();

        setTheClass(PosTransactionOutReturToMainKitchen.class);
        
        setPageDetail(ReturDetail.class);
        
        
        returId = new Field();
        returId.setName("returId");
        returId.setCaption("id");
        //returId.setInfo("retur id");
        returId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returId.setInputProperties(" size=\"20\"");        
        getFields().add(returId);
        
        returDate = new Field();
        returDate.setName("returDate");
        returDate.setCaption("date");
        returDate.setRequired(true);
        returDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        returDate.setInputProperties(" size=\"8\"");
        returDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(returDate);
        
        returNumber = new Field();
        returNumber.setName("returNumber");
        returNumber.setCaption("number");
        returNumber.setRequired(true);
        returNumber.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        returNumber.setInputProperties(" size=\"30\" readonly");        
        getFields().add(returNumber);
        
        returQuantity = new Field();
        returQuantity.setName("returQuantity");
        returQuantity.setCaption("quantity");
        //returQuantity.setInfo("retur quantity");
        returQuantity.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        returQuantity.setInputProperties(" size=\"20\"");        
        getFields().add(returQuantity);
        
        returDescription = new Field();
        returDescription.setName("returDescription");
        returDescription.setCaption("description");
        //returDescription.setInfo("retur description");
        returDescription.setListProperties(" align=\"left\" width=\"40%\" nowrap");
        returDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        returDescription.setInputType(Field.INPUT_TEXT_AREA);
        returDescription.setInputCase(Field.CASE_UPPER);          
        getFields().add(returDescription);
        
        returTimestamp = new Field();
        returTimestamp.setName("returTimestamp");
        returTimestamp.setCaption("retur timestamp");
        //returTimestamp.setInfo("retur timestamp");
        returTimestamp.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        returTimestamp.setInputProperties(" size=\"12\"");
//        returTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(returTimestamp);
        
        returUserId = new Field();
        returUserId.setName("returUserId");
        returUserId.setCaption("user");
        //posTransactionReturToMainKitchenDetailCollection.setInfo("pos transaction retur to main kitchen detail collection");
        returUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returUserId.setInputProperties(" size=\"20\"");        
        getFields().add(returUserId);
        
        returUnitId = new Field();
        returUnitId.setName("returUnitId");
        returUnitId.setCaption("unit");
        //posTransactionReturToMainKitchenCollection.setInfo("pos transaction retur to main kitchen collection");
        returUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returUnitId.setInputProperties(" size=\"20\"");        
        getFields().add(returUnitId);
        
        returReceiptId = new Field();
        returReceiptId.setName("returReceiptId");
        returReceiptId.setCaption("receipt");
        returReceiptId.setRequired(true);
        returReceiptId.setSelectorLoad(true);
        returReceiptId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        returReceiptId.setInputProperties(" size=\"20\""); 
//        returReceiptId.setSelectorCondition("t.receiptKeel='1'");
        returReceiptId.getSelectorColumns().add(new String[]{"receiptNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
//        returReceiptId.getSelectorColumns().add(new String[]{"receiptTotal", " Total ", "align=\"right\" width=\"10%\""});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptQuantity", " Quantity", " align=\"center\" width=\"10%\" nowrap"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptDescription", " Description", "align=\"left\" width=\"60%\""});
        returReceiptId.setSelectorOrder("t.receiptNumber");
        getFields().add(returReceiptId);
        
        returPosUnitId = new Field();
        returPosUnitId.setName("returPosUnitId");
        returPosUnitId.setCaption("pos unit");
//        posMasterMainKitchen.setInfo("pos master main kitchen");
        returPosUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returPosUnitId.setInputProperties(" size=\"20\"");        
        getFields().add(returPosUnitId);
        
        returRegionalId = new Field();
        returRegionalId.setName("returRegionalId");
        returRegionalId.setCaption("regional");
        //posMasterRegional.setInfo("pos master regional");
        returRegionalId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returRegionalId.setInputProperties(" size=\"20\"");        
        getFields().add(returRegionalId);
        
        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        
        fillFields();
        
        getFieldsAdd().clear();
        getFieldsAdd().add(returNumber);
        getFieldsAdd().add(returReceiptId);
//        getFieldsAdd().add(returRegionalId);
        getFieldsAdd().add(returDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(returNumber);
        getFieldsEdit().add(returReceiptId);
//        getFieldsEdit().add(returRegionalId);
        getFieldsEdit().add(returDescription);

        getFieldsList().clear();
        getFieldsList().add(returNumber);
        getFieldsList().add(returReceiptId);
//        getFieldsList().add(returRegionalId);
        getFieldsList().add(returDate);
        getFieldsList().add(returQuantity);
//        getFieldsList().add(returPosUnitId);
        getFieldsList().add(returDescription);

        getFieldsView().clear();
        getFieldsView().add(returDate);
        getFieldsView().add(returNumber);
        getFieldsView().add(returQuantity);
        getFieldsView().add(returReceiptId);
//        getFieldsView().add(returPosUnitId); 
        getFieldsView().add(returTimestamp);
        getFieldsView().add(returDescription);
        
        setController(new Controller(this) {
            @Override
            public void beforeInsert(Object data, List list) {
                PosTransactionOutReturToMainKitchen retur = (PosTransactionOutReturToMainKitchen) data;
                EntityManager em = getEntityManager();
                retur.setReturNumber(generate());
                retur.setReturUnitId(getCurrentUnit());
                retur.setReturUserId(getCurrentUser());
                retur.setReturTimestamp(Utility.getTimestamp());
                retur.setReturDate(Utility.getTimestamp());


            }

            @Override
            public void afterInsert(Object data, List list) {

                EntityManager em = getEntityManager();
                PosMasterStatus statusGood = Status.getStatusGood(em);
                try {
                    em.getTransaction().begin();
                    PosTransactionOutReturToMainKitchen retur = (PosTransactionOutReturToMainKitchen) data;
//                    retur.setReturPosUnitId(retur.getReturReceiptId().getReceiptPosUnitId());
//                    retur.setReturRegionalId(retur.getReturReceiptId().getReceiptRegionalId());
                    
                    BigDecimal total = BigDecimal.ZERO;
                    BigDecimal totalQuantity = BigDecimal.ZERO;
                    String desc = "";
                    for (Object detail : list) {
                        PosTransactionOutReturToMkDetail returDetail = (PosTransactionOutReturToMkDetail) detail;

                        
                        PosMasterItemStock stock = Item.getStockItem(em, returDetail.getReturDetailItemId(), getCurrentUnit());
                        PosTransactionItemStock itemStock = new PosTransactionItemStock();

                        itemStock.setItemStockId(Sequence.next(itemStock));
                        itemStock.setItemStockItemId(returDetail.getReturDetailItemId());
                        itemStock.setItemStockUnitId(getCurrentUnit());
//                        itemStock.setItemStockStatusId(statusGood);
                        itemStock.setItemStockType("@");
//                        itemStock.setItemStockRegionalId(retur.getReturRegionalId());
//                        itemStock.setItemStockPosUnitId(retur.getReturPosUnitId());
                        itemStock.setItemStockLast(stock.getItemStockValue());
                        itemStock.setItemStockValue(returDetail.getReturDetailQuantity());
                        itemStock.setItemStockCurrent(stock.getItemStockValue().subtract(itemStock.getItemStockValue()));
                        itemStock.setItemStockUserId(getCurrentUser());
                        itemStock.setItemStockTimestamp(Utility.getTimestamp());
                        System.out.println(itemStock.getItemStockId() + "<<=========dedy=");
                        em.persist(itemStock);
                        stock.setItemStockValue(itemStock.getItemStockCurrent());
                        total = total.add(returDetail.getReturDetailPrice().multiply(returDetail.getReturDetailQuantity()));
                        totalQuantity = totalQuantity.add(returDetail.getReturDetailQuantity());
                    
                        desc = desc + "Retur " + returDetail.getReturDetailItemId() + " Quantity = " + returDetail.getReturDetailQuantity()
                            + " Dengan Harga = " + returDetail.getReturDetailPrice()
                            + ". ";
                    }
                    
                   retur.setReturDescription(desc);
                   retur.getReturReceiptId().setReceiptDescription(desc); 
                    retur.getReturReceiptId().setReceiptUnpaid(retur.getReturReceiptId().getReceiptUnpaid().subtract(total));
                    retur.setReturQuantity(totalQuantity);
                    em.getTransaction().commit();
                } catch (Exception e) {
                }
            }
        });
    }
    
    
    @Override
    public void beforeAdd() {
        returNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionOutReturToMainKitchen rec = (PosTransactionOutReturToMainKitchen) getEntityManager().createQuery("SELECT t FROM PosTransactionMkReturToMainKitchen t "
                    + "WHERE t.returNumber LIKE '%/" + unitCode + "/Rons/RET-MainKitchen/%/" + year + "' "
                    + "ORDER BY t.returTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getReturNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/RET-MainKitchen/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/RET-MainKitchen/" + month + "/" + year;
    }
}
